package com.l.Thread.Lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock
 * lock()       显示开启锁
 * unlock()     显示释放锁
 * 与synchronized具有相同的功能
 * 解释：try---finally{unlock()}      不会因为异常的中止，而导致无法释放锁，进行搭配使用
 *
 * @author Mc.Chai
 * @program: Java基础
 * @create 2021-11-16-20:11 20:11
 */
public class TestReentrantLock {
    public static void main(String[] args) {
        System.out.println("--程序开始---");
        MyList myList=new MyList();
        new Thread(){
            @Override
            public void run() {
                for (char i = 'B'; i < 'E'; i++) {
                    myList.add(i+"");
                }
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                for (char i = 'B'; i < 'E'; i++) {
                    myList.add(i+"");
                }
            }
        }.start();
        System.out.println("--程序结束---");

    }
}
class MyList {
    private Lock locker=new ReentrantLock();        //创建重入锁对象
    private String[] strings=new String[]{"A","B","","",""};
    private  int count=2;  //元素的个数

    public  void add(String value){

        locker.lock();  //显示开启锁
        try {
            if (count<=4){
                if (strings[count]=="") {
                    strings[count]=value;
                    System.out.println(Thread.currentThread().getName()+"已赋值"+value);
                }
            }else{
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count++;
        } finally {
            locker.unlock();//显示释放锁
        }
    }

}
